package me.zxk.smartagriculture.exception;

import lombok.extern.slf4j.Slf4j;
import me.zxk.smartagriculture.common.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        log.warn("参数校验失败: {}", errors);

        // 构建详细的错误消息
        StringBuilder messageBuilder = new StringBuilder("参数校验失败: ");
        errors.forEach((field, message) -> {
            messageBuilder.append(field).append("(").append(message).append("), ");
        });

        // 移除最后的逗号和空格
        String finalMessage = messageBuilder.toString();
        if (finalMessage.endsWith(", ")) {
            finalMessage = finalMessage.substring(0, finalMessage.length() - 2);
        }

        return ApiResponse.error(400, finalMessage);
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Object> handleBindException(BindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        log.warn("参数绑定失败: {}", errors);

        // 构建详细的错误消息
        StringBuilder messageBuilder = new StringBuilder("参数格式错误: ");
        errors.forEach((field, message) -> {
            messageBuilder.append(field).append("(").append(message).append("), ");
        });

        // 移除最后的逗号和空格
        String finalMessage = messageBuilder.toString();
        if (finalMessage.endsWith(", ")) {
            finalMessage = finalMessage.substring(0, finalMessage.length() - 2);
        }

        return ApiResponse.error(400, finalMessage);
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Object> handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常: ", ex);
        return ApiResponse.error(500, ex.getMessage());
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Object> handleException(Exception ex) {
        log.error("系统异常: ", ex);
        return ApiResponse.error(500, "系统内部错误");
    }
}
